package com.polaris.live.ui.party.music

import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.blankj.utilcode.util.ColorUtils
import com.polaris.live.R

/**
 * MusicCircleView
 *
 * @author Created by 半仙 on 2023/10/27/027 19:34
 */
class MusicCircleView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private var progress = 0f
    private var animator: ValueAnimator? = null

    private val paint = Paint()
    private val backgroundPaint = Paint()

    var onAnimationEnd: (() -> Unit)? = null

    fun setAnimationCallback(callback: () -> Unit) {
        onAnimationEnd = callback
    }

    var onAnimationStart: (() -> Unit)? = null

    fun setAnimationStartCallback(callback: () -> Unit) {
        onAnimationStart = callback
    }

    fun anewRun() {
        if (animator?.isRunning == true) {
            animator?.cancel()
        }
        animator = ValueAnimator.ofFloat(0f, -360f).apply {
            duration = 10000
            repeatCount = 0
            addUpdateListener { animation ->
                progress = animation.animatedValue as Float
                invalidate() // 刷新视图，重新绘制圆环
            }
            addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {
                    onAnimationStart?.invoke()
                }

                override fun onAnimationEnd(animation: Animator) {
                    onAnimationEnd?.invoke()
                }

                override fun onAnimationCancel(animation: Animator) {
                }

                override fun onAnimationRepeat(animation: Animator) {
                }
            })
            start()
        }
    }

    fun setProgress(p: Float) {
        progress = 360f - p * 360f
        invalidate() // 刷新视图，重新绘制圆环
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val centerX = width / 2f
        val centerY = height / 2f
        val radius = (width / 2f) - 10f

        paint.apply {
            style = Paint.Style.STROKE
            strokeWidth = 10f
        }
        paint.color = ColorUtils.getColor(R.color.roomSwitchSelectColor)

        backgroundPaint.apply {
            style = Paint.Style.STROKE
            strokeWidth = 10f
            color = ColorUtils.getColor(R.color.color_000000)
        }

        // 绘制背景圆弧
        canvas.drawArc(
            centerX - radius, centerY - radius, centerX + radius, centerY + radius,
            -90f, 360f, false, backgroundPaint
        )


        canvas.drawArc(
            centerX - radius + 2f, centerY - radius + 2f, centerX + radius - 2f, centerY + radius - 2f,
            -90f, progress, false, paint
        ) // 绘制圆弧
    }
}